package demo.javax.sql;

import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.mchange.v2.c3p0.ComboPooledDataSource;

import demo.java.lang.ThreadDemo;
import demo.java.sql.ConnectionDemo;

public class DataSourceDemo {

    private static Logger logger = LoggerFactory.getLogger(DataSourceDemo.class);

    public static String localUrl = "jdbc:mysql://127.0.0.1:3306/db2019", localUser = "root", localPass = "123456";
    public static final String localJDBCURL = "jdbc:mysql://127.0.0.1:3306/db2019?user=root&password=123456&useUnicode=true&characterEncoding=utf8";

    public static String xdcsUrl = "jdbc:mysql://192.168.3.161:3306/xdcs_home", xdcsUser = "naliworld",
            xdcsPass = "password!";

    public static DataSource local = TomcatDataSourceDemo.initMySqlDataSource(localUrl, localUser, localPass);

    /**
     * 获取连接超时。
     * <li>如果超过maxActive，再获取连接时回报超时
     * <li>如果未超过maxActive，网络断开时，也会报超时
     */
    @Test
    public void testDruidGetConnectionTimeoutException() {
        try (DruidDataSource ds = DruidDataSourceDemo.initDataSource(xdcsUrl, xdcsUser, xdcsPass)) {
            int cnt = 0;
            while (true) {
                long t0 = System.currentTimeMillis();
                DruidPooledConnection connection = ds.getConnection();
                long cost = System.currentTimeMillis() - t0;
                ConnectionDemo.printTransactionIsolation(connection);
                logger.info(" get Connection cnt = {}, cost:{} ms", ++cnt, cost);
                ThreadDemo.safeSleep(500);
            }
        } catch (SQLException e) {
            logger.error("com.alibaba.druid.pool.GetConnectionTimeoutException:", e);
        }
    }

    /**
     * 获取连接超时。
     * <li>如果超过maxActive，再获取连接时回报超时
     * <li>如果未超过maxActive，网络断开时，也会报超时
     */
    @Test
    public void testC3P0GetConnectionTimeoutException() {
        ComboPooledDataSource ds = null;
        try {
            ds = ComboPooledDataSourceDemo.init(xdcsUrl, xdcsUser, xdcsPass);
            int cnt = 0;
            while (true) {
                long t0 = System.currentTimeMillis();
                Connection connection = ds.getConnection();
                long cost = System.currentTimeMillis() - t0;
                ConnectionDemo.printTransactionIsolation(connection);
                logger.info(" get Connection cnt = {}, cost:{} ms", ++cnt, cost);
                ThreadDemo.safeSleep(500);
            }
        } catch (SQLException e) {
            logger.error("com.mchange.v2.resourcepool.TimeoutException:", e);
        } catch (PropertyVetoException e) {
            logger.error("", e);
        } finally {
            if (ds != null) {
                ds.close();
            }
        }
    }

}
